package main

import (
	"fmt"
	"go_stu/5_grpc_stu/4_stream_grpc_test/protos"
	"net"
	"sync"
	"time"

	"google.golang.org/grpc"
)

const PORT = ":50052"

type Server struct {
	protos.UnimplementedGreaterServer
}

func (s *Server) GetStream(req *protos.StreamReqData, res protos.Greater_GetStreamServer) error {
	i := 0
	for {
		i++
		res.Send(&protos.StreamResData{Data: fmt.Sprintf("%v", time.Now().Unix())})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}
	return nil
}

func (s *Server) PutStream(req protos.Greater_PutStreamServer) error {
	for {
		if a, err := req.Recv(); err != nil {
			fmt.Println(err)
			break
		} else {
			fmt.Println(a.Data)
		}
	}
	return nil
}

func (s *Server) AllStream(req protos.Greater_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := req.Recv()
			fmt.Println("收到：" + data.Data)
		}
	}()
	go func() {
		defer wg.Done()
		for {
			_ = req.Send(&protos.StreamResData{Data: "我是服务器"})
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()
	return nil
}

func main() {
	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		panic(err.Error())
	}
	s := grpc.NewServer()
	protos.RegisterGreaterServer(s, &Server{})
	s.Serve(lis)
}
